/*  
 * @(#) SessinoFilter.java Create on 2012-5-8 上午11:45:28   
 *   
 * Copyright 2012 by xl.   
 */

package cn.com.common.interceptor;

import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.springframework.stereotype.Controller;

import cn.com.common.base.action.BaseAction;
import cn.com.common.base.bean.BackstageResult;
import cn.tools.CommonSendMeg;
import cn.tools.jackjson.JackJson;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;

/**
 * 异常拦截器
 * 
 * <ul>
 * <li>
 * 所以的action，service，dao都throws Exception异常信息统一在此打印</li>
 * <li>
 * 判断请求是否为ajax，请求参数中带有_r=a 标识为ajax请求,如果为ajax请求需写到页面错误值</li>
 * </ul>
 * 
 * @author zhanghongliang
 * @date 2012-5-8
 */
@Controller
public class ExceptionInterceptor extends BaseAction implements Interceptor {
	private Logger log = Logger.getLogger(ExceptionInterceptor.class);
	private static final long serialVersionUID = 1L;

	@Override
	public void destroy() {
		if (log.isDebugEnabled())
			log.debug("ExceptionInterceptor destroy...");
	}

	@Override
	public void init() {
		if (log.isDebugEnabled())
			log.debug("ExceptionInterceptor init...");
	}

	@Override
	public String intercept(ActionInvocation aic) throws Exception {
		try {
			return aic.invoke();
		} catch (Exception e) {
			log.error(ExceptionUtils.getFullStackTrace(e));
			Object requestType = getFromRequestParameter("_r");
			// 是ajax请求
			if ("a".equals(requestType)) {
				BackstageResult result = new BackstageResult(false, e.getMessage());
				CommonSendMeg.writeMsg(ServletActionContext.getResponse(), JackJson.fromObjectToJson(result));
				return "";
			}
		}
		return ERROR;
	}
}
